package com.iweb.controller;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 超人
 * @since 2020-09-10
 */
@RestController
@RequestMapping("/user")
public class UserController {

    // session
    // @PreAuthorize("hasAuthority('session')")
    @GetMapping("/hello")
    public String hello() {
        return "hello :" + getUserName();
    }

    // 获取用户信息
    private String getUserName() {
        String username = null;
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            username = "匿名用户";
            return username;
        }

        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }

    // database
    // @PreAuthorize("hasAuthority('database_all')")
    @GetMapping("/database")
    public String database() {
        return "database :" + getUserName();
    }

    // user
    // @PreAuthorize("hasAuthority('user_all')")
    @GetMapping("/user")
    public String user() {
        return "user :" + getUserName();
    }

    // table
    // @PreAuthorize("hasAuthority('table_all')")
    @GetMapping("/table")
    public String table() {
        return "table :" + getUserName();
    }
}

